package com.example.Controller;

import com.example.Utils.AliOssUtil;
import com.example.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {

        log.info("文件上传------------");

        try{
            // 获取原文件名以及后缀
            String originalFilename = file.getOriginalFilename();
            String back = originalFilename.substring(originalFilename.lastIndexOf('.'));
            // 创建新的文件名
            String fileName =  UUID.randomUUID().toString()+back;
            String upload = aliOssUtil.upload(file.getBytes(), fileName);
            log.info("文件上传到{}",upload);
        }catch (Exception e){
            return Result.error("文件上传失败");
        }

        return Result.success();
    }

    /**
     * 文件删除
     */
    @PostMapping("/delete")
    public Result<String> delete(MultipartFile file){
        return aliOssUtil.delete(file);
    }
}
